import { h } from "vue"
import { TableCellBtn } from "./types"
import UiCellBtns from "../components/CellBtns.vue"
import { FormItemRule, ElMessage } from "element-plus"

export const joinPath = (...paths: string[]) => {
  const sep = '/'
  const [start, ...otherPaths] = paths

  return otherPaths.reduce((t, _) => {
    const subPath = _.replace(/^(\/)+/gm, '')
    return t + (t.endsWith(sep) ? '' : sep) + subPath
  }, start)
}

export const pageSizeManager = (() => {
  const key = '_pageSize'
  return {
    get pageSize () {
      return +localStorage.getItem(key) || 10
    },
    set pageSize (v) {
      localStorage.setItem(key, v as any)
    }
  }
})()

export const genKey = ((k = 1) => () => k++)()

export const isFunc = (v: any) => typeof v === 'function'

export const isObj = (v: any) => typeof v === 'object'

export const isArr = (v: any) => v instanceof Array

export const isEmpty = (v: any) => ['', null, undefined].includes(v)

export const hBtns = (btns: TableCellBtn | TableCellBtn[]) => h(UiCellBtns, { btns })

export const callFunc = <T extends (...args: any) => any>(fn: T, ...args: Parameters<T>) => isFunc(fn) && fn(...args)

export const createNonEmptyRule = (message: string): FormItemRule => {
  return { trigger: 'blur', required: true, pattern: /\S+/, message }
}

export const createRequiredRule = (message: string): FormItemRule => ({ required: true, message })

export const createNonNegativeIntRule = (message: string = '请输入非负整数值'): FormItemRule => {
  return { message, trigger: 'blur', pattern: /^\d+$/ }
}

export const throwError = (msg: any) => {
  ElMessage.warning(msg)
  return Promise.reject(new Error(msg))
}

export const deepCopy = <T>(obj: T): T => JSON.parse(JSON.stringify(obj))
